<template>

  <h2 class="title">{{ surveyTitle }}</h2>
  <uni-notice-bar show-icon text="测评时不要有过多思考，尽量根据自己的第一想法，确保测评结果更加准确" />
  <uni-forms ref="formRef" :model="formState" :rules="dynamicRules" :validate-trigger="'submit'">
    <!-- 题目循环渲染区域 -->
    <view v-for="(question, index) in surveyData" :key="question.id" class="question-card"
      :class="{ required: question.required }">
      <!-- 题目标题 -->
      <view class="question-header">
        {{ index + 1 }}. {{ question.title }}
      </view>

      <!-- 条件渲染不同类型题目 -->
      <uni-forms-item :name="`q_${question.id}`" :required="question.required">
        <!-- 单选题型 -->
        <template v-if="question.type === 'radio'">
          <radio-group>
            <!-- 遍历选项时增加 score 参数传递 -->
            <view v-for="opt in question.options" :key="opt.value" class="option-item">
              <label class="option-label"
                @click="handleRadioChange(question.id, opt.score, { detail: { value: opt.value } })">
                <radio :value="opt.value" :checked="formState[`q_${question.id}`] === opt.value" color="#007AFF" />
                <text class="option-text">{{ opt.label }}</text>
              </label>
              <text class="option-score" v-if="showScorePreivew">+{{ opt.score }}分</text>
            </view>
          </radio-group>
        </template>

        <!-- 多选题型 -->
        <template v-else-if="question.type === 'checkbox'">
          <checkbox-group @change="(e) => handleCheckboxChange(question, e)">
            <view v-for="opt in question.options" :key="opt.value" class="option-item">
              <label class="option-label" @click.stop="noop">
                <checkbox :value="opt.value" :checked="(formState[`q_${question.id}`] || []).indexOf(opt.value) > -1"
                  color="#007AFF" />
                <text class="option-text">{{ opt.label }}</text>
              </label>
              <text class="option-score" v-if="showScorePreivew">+{{ opt.score }}分</text>
            </view>
          </checkbox-group>
          <text v-if="question.maxSelect" class="select-limit">
            （最多选择{{ question.maxSelect }}项）
          </text>
        </template>

        <!-- 填空题型 -->
        <template v-else-if="question.type === 'text'">
          <textarea v-model="formState[`q_${question.id}`]" class="answer-textarea"
            :placeholder="question.placeholder || '请输入内容...'" :maxlength="question.maxLength" auto-height
            @input="() => handleTextUpdate(question)" />
          <view v-if="question.maxLength" class="text-counter">
            {{ formState[`q_${question.id}`]?.length || 0 }}/{{ question.maxLength }}
          </view>
        </template>
      </uni-forms-item>
    </view>
    <view>
      <!-- 提示窗示例 -->
      <uni-popup ref="overcome" type="dialog">
        <uni-popup-dialog :type="msgType" cancelText="关闭" confirmText="同意" title="通知" :content="evaluate"
          @confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
      </uni-popup>
    </view>

    <!-- 操作面板 -->
    <view class="action-panel">
      <view class="total-score" v-if="false">当前总分: {{ currentScore }}</view>
      <button type="primary" class="submit-btn" @click="validateForm('success')">
        提交答卷
      </button>
    </view>
  </uni-forms>
</template>

<script>
// import survey from '../../../static/js/mock'
// import Alsurvey from '../../../static/js/AIsurvey'
// import creativitySurvey_1 from '../../../static/js/creativitySurvey_1'
// import creativitySurvey_2 from '../../../static/js/creativitySurvey_2'


export default {
  props: {
    // 问卷数据结构传入
    // surveyData: {
    //   type: Array,
    //   required: true,
    //   validator: (value) => {
    //     return value.every(q => ['radio', 'checkbox', 'text'].includes(q.type))
    //   }
    // },
    // 是否显示得分预览
    showScorePreivew: {
      type: Boolean,
      default: false
    }
  },
  onLoad(options) {
    const { surveyId } = options
    // 动态导入问卷数据
    this.surveyId = surveyId
    this.loadSurveyModule(surveyId)
      .then(surveyModule => {
        this.surveyData = surveyModule.survey;
        this.surveyTitle = this.surveyData.title;
        // 其他初始化操作
      })
      .catch(error => {
        console.error('加载问卷模块失败:', error);
        // 处理错误，如显示错误提示
      });
    // this.surveyData = {
    //   'Alsurvey': Alsurvey.survey,
    //   'creativitySurvey_1': creativitySurvey_1.survey,
    //   'creativitySurvey_2': creativitySurvey_2.survey
    // }[surveyId]
    // this.surveyTitle = this.surveyData.title


  },
  data() {
    return {
      // 问卷数据 
      surveyData: [],
      surveyTitle: "问卷自测",
      surveyId: '',
      // 记录题目id与选项标识（value）
      formState: {},         // 表单数据存储 题目/选项 映射表
      currentScore: 0,      // 当前总得分
      //每题的得分
      scoreMap: new Map(),   // 得分缓存（题号:得分）
      evaluate: '',
      msgType: 'success',
      Alsurvey: () => import('../../../static/js/AIsurvey')
    }
  },
  mounted() {
    //判断登录态
    if (!this.isLogin) {
      uni.showModal({
        title: '提示',
        content: '未登录,问卷结果将无法保存,请先登录',
        success: function (res) {
          if (res.confirm) {
            uni.navigateBack({
              delta: 2
            });

          } else if (res.cancel) {
            uni.navigateBack({
              delta: 2
            });
          }
        }
      });

    }
  },
  computed: {
    // 动态规则生成器
    dynamicRules() {
      const generateRule = (question) => {
        const rules = []
        if (question.required) {
          rules.push({
            required: true,
            errorMessage: `请填写【${question.title}】`,
            validateTrigger: 'submit'
          })
        }
        if (question.type === 'checkbox' && question.maxSelect) {
          rules.push({
            validate: (val) => !val || val.length <= question.maxSelect,
            errorMessage: `最多选择${question.maxSelect}项`,
            trigger: 'change'
          })
        }
        // 多选题时 的规则可能是 最多选x项，也可能必选x项
        if (question.type === 'checkbox' && question.minSelect) {
          rules.push({
            validateFunction: function (rule, value, data, callback) {
              if (value.length < minSelect) {
                callback('请至少勾选' + minSelect + '个选项')
              }
            }
          })
        }
        return rules
      }

      return this.surveyData.reduce((rules, q) => {
        rules[`q_${q.id}`] = { rules: generateRule(q) }
        return rules
      }, {})
    },
    isLogin() {
      return uni.getStorageSync('isLogin') && uni.getStorageSync('token');

    }
  },
  methods: {

    // 动态导入静态资源 （新增 后期根据服务端进行修改）
    async loadSurveyModule(surveyId) {
      switch (surveyId) {
        case 'Alsurvey':
          return (await import('../../../static/js/AIsurvey')).default;
        case 'creativitySurvey_1':
          return (await import('../../../static/js/creativitySurvey_1')).default;
        case 'creativitySurvey_2':
          return (await import('../../../static/js/creativitySurvey_2')).default;
        default:
          throw new Error(`未知的surveyId: ${surveyId}`);
      }
    },

    // 辅助方法：根据选项值查找分数（假设题目数据中有 score 字段）
    getScoreByValue(questionId, value) {
      const question = this.surveyData.find(q => q.id === questionId);
      const option = question.options.find(opt => opt.value === value);
      return option?.score || 0;
    },
    // 单选框变更处理
    // 修改后的方法（直接接受 score）
    handleRadioChange(questionId, score, event) {
      const key = `q_${questionId}`
      const oldValue = this.formState[key]

      // 选择重复的选项时， 返回即可
      if (oldValue === event.detail.value) {
        return
      }
      // 选择不同的选项时 去除旧选项的分数
      if (oldValue) {
        const oldScore = this.getScoreByValue(questionId, oldValue)
        this.currentScore -= oldScore
        this.scoreMap.delete(questionId)
      }
      const newValue = event.detail.value
      const newScore = score
      this.currentScore += newScore;
      this.scoreMap.set(`q_${questionId}`, newScore);
      this.$set(this.formState, key, newValue);

    },
    handleCheckboxChange(question, event) {
      const questionId = question.id;
      const key = `q_${questionId}`;

      const newSelection = Array.from(event.detail.value);

      // 记录当前时间戳用于竞态校验
      const timestamp = Date.now();
      this.lastHandleTimestamp = timestamp;

      this.$set(this.formState, key, newSelection);

      this.$nextTick(() => {
        // 增加竞态校验：只有最后一次操作会被处理
        if (timestamp !== this.lastHandleTimestamp) return;

        // 增强型一致性校验
        const storedValue = this.formState[key] || [];
        if (JSON.stringify(storedValue) !== JSON.stringify(newSelection)) return;

        // 尝试添加防抖
        // 使用更健壮的分数计算方法
        const calculateActualScore = (selectedValues) => {
          return selectedValues.reduce((sum, value) => {
            // 精确匹配选项（类型安全比较）
            const option = question.options.find(opt => String(opt.value) === String(value));
            return sum + (Number(option?.score) || 0);
          }, 0);
        };

        // 确保获取旧分数的准确性
        const oldScore = this.scoreMap.has(questionId)
          ? this.scoreMap.get(questionId)
          : 0;

        // 计算实际有效分数
        const effectiveScore = calculateActualScore(newSelection);

        // 【核心修正】当没有有效分数时清除记录
        if (effectiveScore === 0) {
          const updatedMap = new Map(this.scoreMap);
          updatedMap.delete(questionId);  // 代替设置0值
          this.scoreMap = updatedMap;
        } else {
          const updatedMap = new Map(this.scoreMap);
          updatedMap.set(questionId, effectiveScore);
          this.scoreMap = updatedMap;
        }

        // 原子性更新总分
        this.currentScore += (effectiveScore - oldScore);

        // 调试信息增强
        console.log('处理详情：', {
          questionId,
          旧分数: oldScore,
          新分数: effectiveScore,
          总分变化: effectiveScore - oldScore,
          当前总分: this.currentScore,
          当前选项: [...newSelection]
        });
      });
    },


    // 文本域更新处理
    handleTextUpdate(question) {
      // 文本题得分计算示例
      const score = Math.min(this.formState[`q_${question.id}`]?.length || 0, 10)
      this.scoreMap.set(question.id, score)
      this.updateTotalScore()
    },

    // 单题得分计算
    calculateQuestionScore(question, selectedValues) {
      let score = 0
      switch (question.type) {
        case 'radio':
          score = (question.options.find(o => o.value === selectedValues[0]?.score) || 0)
          break
        case 'checkbox':
          score = selectedValues.reduce((total, value) => {
            return total + (question.options.find(o => o.value === value)?.score || 0)
          }, 0)
          break
      }
      this.scoreMap.set(question.id, score)
      this.updateTotalScore()
    },



    // 执行表单验证
    async validateForm(type) {

      await this.$refs.formRef.validate()
        .then(() => this.$emit('submit', this.getResultData()))
        .catch(errors => this.handleValidationError(errors))

      this.handleSurveyEvaluation(this.surveyId, this.currentScore)

    },
    handleSurveyEvaluation(surveyId, currentScore) {
      let evaluation;
      switch (surveyId) {
        case 'Alsurvey':
          evaluation = this.evaluateAlSurvey(currentScore);
          break;
        case 'creativitySurvey_1':
          evaluation = this.evaluateCreativitySurvey1(currentScore);
          break;
        case 'creativitySurvey_2':
          evaluation = this.evaluateCreativitySurvey2(currentScore);
          break;
        default:
          console.error('未知的 surveyId:', surveyId);
          return;
      }
      if (surveyId === 'AIsurvey') {
        this.surveyTitle = 'AI系列测评'
      } else if (surveyId === 'creativitySurvey_1') {
        this.surveyTitle = '创意系列测评1'
      } else {
        this.surveyTitle = '创意系列测评2'
      }

      // 跳转到 overcome 页面并传递分数和评价参数
      // 这里假设使用 uni-app 的跳转方法，根据实际情况修改
      uni.navigateTo({
        url: `overcome?surveyTitle=${this.surveyTitle}&score=${evaluation.score}&rank=${evaluation.rank}`
      });
    },
    evaluateAlSurvey(score) {
      let rank;
      if (score > 135) {
        rank = '您对AI的了解已经炉火纯青了';
      } else if (score >= 120 && score <= 134) {
        rank = '您对AI的了解已经很强了,快去炫耀一下吧';
      } else if (score >= 90 && score <= 119) {
        rank = '您对AI的了解很不错,继续加油';
      } else {
        rank = '您对AI的了解还差点意思，需要继续努力！';
      }
      return { score, rank };
    },
    evaluateCreativitySurvey1(score) {
      let rank;
      if (score > 110 && score < 140) {
        rank = '创造力优秀，适合创意类职业（如设计、策划）';
      } else if (score >= 85 && score <= 109) {
        rank = '创造力良好，适合较强创造性工作（如软件开发）';
      } else if (score >= 90 && score <= 119) {
        rank = '创造力一般，需针对性提升';
      } else {
        rank = '创造力较弱，更适合规则明确的工作。';
      }
      return { score, rank };
    }
    ,
    evaluateCreativitySurvey2(score) {
      let rank;
      if (score >= 110 && score <= 140) {
        rank = '创造力非凡';
      } else if (score >= 85 && score <= 109) {
        rank = '创造力很强';
      } else if (score >= 56 && score <= 84) {
        rank = '创造力强';
      } else if (score >= 30 && score <= 55) {
        rank = '创造力一般';
      } else if (score >= 15 && score <= 29) {
        rank = '创造力弱';
      } else {
        rank = '无创造力!';
      }
      return { score, rank };
    },
    // 获取结构化结果数据
    getResultData() {
      return {
        formData: { ...this.formState },        // 原始答案数据
        scoreDetail: Object.fromEntries(this.scoreMap), // 各题得分详情
        totalScore: this.currentScore           // 总分
      }
    },

    // 处理验证错误
    handleValidationError(errors) {
      const firstError = Object.values(errors)[0]
      uni.showToast({
        title: firstError[0].errorMessage,
        icon: 'none',
        position: 'bottom'
      })
    },



  }
}

</script>

<style lang="scss">
.title {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 10px;
  text-align: center;
}

.question-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

  &.required .question-header::after {
    content: "*";
    color: #EB2F2F;
    margin-left: 8rpx;
  }
}

.question-header {
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 24rpx;
  color: #333;
}

.option-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.option-label {
  flex: 1;
  display: flex;
  align-items: center;
}

.option-text {
  margin-left: 16rpx;
  color: #666;
}

.option-score {
  font-size: 24rpx;
  color: #4CAF50;
}

.select-limit {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-top: 16rpx;
}

.answer-textarea {
  width: 100%;
  min-height: 180rpx;
  padding: 20rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.text-counter {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.action-panel {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 24rpx;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.total-score {
  text-align: center;
  font-size: 32rpx;
  color: #007AFF;
  margin-bottom: 32rpx;
  font-weight: bold;
}

.submit-btn {
  margin-top: 24rpx;
}
</style>
